import  { constantRoutes, dynamicRoutes } from '@/router'
import {getRouters} from '@/api/menu'
import Layout from '@/layout/index'
// import auth from '@/plugins/auth'

//匹配权限
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}


/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []
    routes.forEach(route => {
        const tmp = { ...route }
        if (tmp.component === 'Layout'){
            tmp.component = Layout
        }else {
            tmp.component = loadView(tmp.component)
        }
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })

    return res
}

export const loadView = (view) => {
    if (process.env.NODE_ENV === 'development') {
        return (resolve) => require([`@/views/${view}`], resolve)
    } else {
        // 使用 import 实现生产环境的路由懒加载
        return () => import(`@/views/${view}`)
    }
}


const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.routes = constantRoutes.concat(routes)
        state.addRoutes = routes
    }
}

const actions = {
    generateRoutes({ commit }, roles) {
        return new Promise(resolve => {
            getRouters().then(res =>{
                const accessedRoutes = filterAsyncRoutes(res.data , roles);
                // if (roles.includes('admin')) {
                //     accessedRoutes = dynamicRoutes || []
                //     console.log("是admin")
                //     console.log(accessedRoutes)
                // } else {
                //     console.log("不是admin")
                //     accessedRoutes = filterAsyncRoutes(dynamicRoutes, roles)
                // }
                commit('SET_ROUTES', accessedRoutes)
                resolve(accessedRoutes)
            })

        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
